<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 项目接口相关
 */
class Project extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 处理转入下一年
     */
    public function switchyear(){
        //处理年份
        $year = date("Y");
        $baseTableName = "nsig_project_2020";
//        $year = 2021;
        $dbname = config('database.dbname');
        $table_name_arr = Db::query("SELECT table_name FROM information_schema.TABLES WHERE TABLE_SCHEMA='{$dbname}'");
        $table_name_arr = array_column($table_name_arr, 'table_name');
        $push_table_name = config('database.prefix').'project_' . $year;
        $sql = "CREATE TABLE IF NOT EXISTS $push_table_name LIKE $baseTableName";
        if (!in_array($push_table_name, $table_name_arr)) {
            Db::execute($sql);
        }

        //处理数据
        //获取需要处理的数据
        $list = Db::name('project_year_switch')
            -> where('toyear',$year)
            -> select();

        $data = [];
        $toTableName = "project_".$year;
        foreach ($list as $k => $v){
            if(!$v['fromyear'] || !$v['toyear'] || !$v['pno']){
                continue;
            }
            $fromTableName = "project_".$v['fromyear'];
            $data[] = Db::name($fromTableName) -> field('id',true) -> where(['pno'=>$v['pno']]) -> find();
        }

        Db::name($toTableName) -> insertAll($data);

    }



    public function swithlibrary(){
        $table = 'project_'.date('Y');
        $rows = Db::name($table)
            -> where(['library_id'    => '1',])
            -> field('id')
            -> where("
if(
	framework_agreement_time > 0 && framework_agreement_time is not null, 
	framework_agreement_time < ".time()." ,
	if(
		invesment_agreement_time > 0 && invesment_agreement_time is not null, 
		invesment_agreement_time < ".time()." ,
		''
	)
)"
            )-> select();


        if($rows){
            $ids = [];
            foreach ($rows as $v){
                $ids[] = $v['id'];
            }
            pr($ids);
            Db::name($table) -> whereIn('id',$ids) -> update([
                'library_id'    => 2,
                'library_name'  => '签约库',
                'is_add'        => 1
            ]);
            Db::name('swithlibrarylog') -> insert([
                'project_ids'   => implode(',',$ids),
                'create_time'   => time(),
                'create_date'   => date('Ymd')
            ]);
        }
    }
}